package com.cyc.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.internal.util.StringUtils;
import com.cyc.entity.CartItem;
import com.cyc.entity.Order;
import com.cyc.entity.OrderDetail;
import com.cyc.service.AlipayService;
import com.cyc.service.OrderDetailService;
import com.cyc.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@RequestMapping("/alipay")
@Controller
//@Log4j
public class PayController {

    @Autowired
    OrderDetailService orderDetailService;

    @Autowired
    ServletContext servletContext;

    @Autowired
    OrderService orderService;

    @Autowired
    AlipayService alipayService;

    @RequestMapping("/pay")
    @ResponseBody
    public byte[] alipay(HttpServletRequest request){
        Order order =(Order) request.getSession().getAttribute("order");
        order.setCost(0.01F);
        return alipayService.alipay(order);
    }


    @ResponseBody
    @RequestMapping("add")
    public String add(Order order,HttpServletRequest request){
        Map<String, Object> map=new HashMap<>();
        order.setCreatetime(new Date());
        request.getSession().setAttribute("order",order);
        map.put("code",1);
        return JSON.toJSONString(map);
    }

    @ResponseBody
    @RequestMapping("/notify")
    public String notify_url(HttpServletRequest request) throws Exception {
        boolean result = alipayCallback(request);
        if (result) {
            return "success"; // 请不要修改或删除
        } else {
            // 验证失败
            return "fail";
        }
    }

    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED)
    boolean alipayCallback(HttpServletRequest request) throws Exception {
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, new String(valueStr.getBytes("ISO-8859-1"), "UTF-8"));
        }

        // 计算得出通知验证结果
//        log.info("1：---->获取支付宝回传的参数---------------------------------->" + params);
        // 返回公共参数
        String extparamString = request.getParameter("extra_common_param");
//        log.info("2---->：支付宝交易返回的参数：{}"+ extparamString);
        String tradeno = params.get("trade_no");;
        //交易完成
        String body = params.get("body");
        if (StringUtils.isEmpty(tradeno)) {
            tradeno = params.get("trade_no");
        }
//        log.info("3---->:【支付宝】交易的参数信息是：{}，流水号是：{}"+ body+ tradeno);
        try {
            JSONObject bodyJson = JSONObject.parseObject(body);
            String userId = bodyJson.getString("userId");
            String loginName=bodyJson.getString("loginName");
            String userAddress=bodyJson.getString("userAddress");
            String ptype = bodyJson.getString("ptype");
            String serialNumber = bodyJson.getString("serialNumber");
            String cost=bodyJson.getString("cost");
//            log.info("4---->:【支付宝】交易的参数信息是：ptype:{}，orderNumber是：{}"+ptype+serialNumber);

            // 支付
            if (ptype != null && ptype.equalsIgnoreCase("easybuy")) {
                Order order=new Order();
                order.setUserid(Integer.valueOf(userId));
                order.setLoginname(loginName);
                order.setCost(Float.valueOf(cost));
                order.setCreatetime(new Date());
                order.setUseraddress(userAddress);
                order.setSerialnumber(serialNumber);
                orderService.insert(order);
                servletContext.setAttribute("orderid",order.getId());
                List<CartItem> list = (List<CartItem>)servletContext.getAttribute("shop");
                if (list!=null){
                    for (CartItem i :list){
                        OrderDetail orderDetail=new OrderDetail();
                        var cost1 = i.getPrice() * i.getNum();
                        orderDetail.setCost(cost1);
                        orderDetail.setOrderid(order.getId());
                        orderDetail.setProductid(i.getId());
                        orderDetail.setQuantity(i.getNum());
                        orderDetailService.insert(orderDetail);
                    }
                    servletContext.removeAttribute("shop");
                }

            }
        } catch (Exception ex) {
//            log.info("支付宝支付出现了异常.....");
            ex.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }





}
